package cn.ht.jywrwater.module.ht.service.town;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.ht.jywrwater.module.ht.controller.admin.town.vo.*;
import cn.ht.jywrwater.module.ht.dal.dataobject.town.TownDO;
import cn.ht.jywrwater.framework.common.pojo.PageResult;

import cn.ht.jywrwater.module.ht.convert.town.TownConvert;
import cn.ht.jywrwater.module.ht.dal.mysql.town.TownMapper;

import static cn.ht.jywrwater.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.ht.jywrwater.module.ht.enums.ErrorCodeConstants.*;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;

/**
 * 乡镇管理 Service 实现类
 *
 * @author hzx
 */
@Service
@Validated
public class TownServiceImpl implements TownService {

    @Resource
    private TownMapper townMapper;

    @Override
    public Long createTown(TownCreateReqVO createReqVO) {
        // 插入
        TownDO town = TownConvert.INSTANCE.convert(createReqVO);
        townMapper.insert(town);
        // 返回
        return town.getId();
    }

    @Override
    public void updateTown(TownUpdateReqVO updateReqVO) {
        // 校验存在
        validateTownExists(updateReqVO.getId());
        // 更新
        TownDO updateObj = TownConvert.INSTANCE.convert(updateReqVO);
        townMapper.updateById(updateObj);
    }

    @Override
    public void deleteTown(Long id) {
        // 校验存在
        validateTownExists(id);
        // 删除
        townMapper.deleteById(id);
    }

    private void validateTownExists(Long id) {
        if (townMapper.selectById(id) == null) {
            throw exception(TOWN_NOT_EXISTS);
        }
    }

    @Override
    public TownDO getTown(Long id) {
        return townMapper.selectById(id);
    }

    @Override
    public List<TownDO> getTownList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return ListUtil.empty();
        }
        return townMapper.selectBatchIds(ids);
    }

    @Override
    public PageResult<TownDO> getTownPage(TownPageReqVO pageReqVO) {
        return townMapper.selectPage(pageReqVO);
    }

    @Override
    public List<TownDO> getTownList(TownExportReqVO exportReqVO) {
        return townMapper.selectList(exportReqVO);
    }

}
